package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.admin.mapper.AdminLoginMapper;
import com.heima.admin.service.AdminLoginService;
import com.heima.model.admin.dtos.AdminLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminLoginServiceImpl implements AdminLoginService {

    @Autowired
    private AdminLoginMapper loginMapper;

    /**
     * 登录
     * @param dto 用户传递的用户名和密码
     * @return
     */
    @Override
    public ResponseResult login(AdminLoginDto dto) {
        //1. 判断用户名密码是否为空
        if(StringUtils.isNotEmpty(dto.getName())&& StringUtils.isNotEmpty(dto.getPassword())){
            //2. 通过用户名查询用户数据
            AdUser adUser = loginMapper.selectOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
            //3. 判断查询到的用户是否为空
            if(null == adUser){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //4. 如果用户存在 判断用户状态是否为正常使用
            Short status = adUser.getStatus();
            if(status != 9){
                //无操作权限
                return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
            }
            //5.1 获取用户的salt,使用md5对其数据加密
            String salt = adUser.getSalt();
            String pwd = dto.getPassword() + salt;
            pwd = DigestUtils.md5DigestAsHex(pwd.getBytes(StandardCharsets.UTF_8));
            //5.2 对比两个密文的密码如果成功则生成token并返回
            if(pwd.equals(adUser.getPassword())){
                String token = AppJwtUtil.getToken((long) adUser.getId());
                //对敏感数据进行隐藏
                adUser.setSalt("");
                adUser.setPassword("");

                //将需要返回的token和aduser封装到map中
                Map<String, Object> result = new HashMap<>();
                result.put("user",adUser);
                result.put("token",token);
                return ResponseResult.okResult(result);
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }
}
